import router from "./router";
import { getToken } from "utils/auth";
import store from "src/store/index";

import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

NProgress.configure({ showSpinner: false }); // NProgress Configuration


const whiteList = ["/home", "/login", "/register"]; // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();
  const hasToken = getToken();

  if (hasToken) {
    if (to.path === "/login") {
      next({ path: "/home" });
    } else {
      if (Object.keys(store.state.user.userInfo).length == 0) {
        store.dispatch("user/getUserInfo");
      }
      // console.log(store.state.permission.accessRoutes.length > 0)
      if (store.state.permission.accessRoutes.length > 0) {
        next();
      } else if (!store.state.permission.isGetAccessRoute) {
        const accessRoutes = await store.dispatch("permission/getMenus")
        accessRoutes.forEach(route => {
          router.addRoute("System", route);
        })
        console.log('accessRoutes',accessRoutes)
        next({ ...to, replace: true })
      } else {
        next();
      }
      next();
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      next(`/login?redirect=${to.fullPath}`);
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
